import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-03-08
 * Time: 15:01
 */
public class JDBCSelect {
    public static void main(String[] args) throws SQLException {
        //1. 创建并初始化
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java107?characterEncoding=utf8&useSSL=false");//向下转型
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        //2. 构建连接
        Connection connection = dataSource.getConnection();
        //3. 构建sql
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
        //4. 执行sql
        ResultSet resultSet = statement.executeQuery();//获得一个entry集合
        //5. 遍历结果集合
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println(id + "\t" + name);
        }
        //6. 释放资源
        resultSet.close();
        statement.close();
        connection.close();

    }
}
